package com.ht.managermentserver.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * json 工具类 类
 *
 * <p>封装jackJson
 *
 * @author czy
 * @package com.ht.managermentserver.utils
 * @date 2020/6/2 9:23
 */
@Component
public class JSONUtil {

  private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
  private static ObjectMapper _OBJECT_MAPPER;

  /**
   * 序列化为 json 字符串
   *
   * @param object 序列化对象
   * @return String json字符串
   */
  public static String toJsonString(final Object object) {

    final ObjectMapper objectMapper = _OBJECT_MAPPER;
    try {
      return objectMapper.writeValueAsString(object);
    } catch (final IOException e) {
      e.printStackTrace();
      return "{}";
    }
  }

  /**
   * json 反序列化,序列化失败时返回 NULL
   *
   * @param jsonStr 反序列化 json 字符串
   * @param type    反序列化对象
   * @param <T>     反序列化对象
   * @return <T>/NUll 对象 或者 null
   */
  public static <T> T parseJson(final String jsonStr, final Class<T> type) {

    final ObjectMapper objectMapper = _OBJECT_MAPPER;
    try {
      return objectMapper.readValue(jsonStr, type);
    } catch (final IOException e) {
      e.printStackTrace();
      return null;
    }
  }

  @Autowired
  public ObjectMapper setObjectMapper(MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter) {
    if (_OBJECT_MAPPER == null) {
      _OBJECT_MAPPER = mappingJackson2HttpMessageConverter.getObjectMapper();
    }
    return _OBJECT_MAPPER;
  }
}
